﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Pumptester.test
{
    public partial class SerialForm : Form
    {
        public SerialForm()
        {
            InitializeComponent();
        }

        public Encoding EncodingType { get; set; } = Encoding.ASCII;

        SerialPort port = new SerialPort();

        private void SerialForm_Load(object sender, EventArgs e)
        {
            
            comboBoxBaudRate.SelectedIndex = 0;
            textBoxData.Text = "8";
            comboBoxCheck.SelectedIndex = 0;
            comboBoxStop.SelectedIndex = 0;

            string[] strCom = SerialPort.GetPortNames();
            if (strCom == null)
            {
                MessageBox.Show("本机没有串口！", "Error");
                return;
            }
            //GetPortNames()方法:获取当前计算机的串行端口名的数组
            foreach (string com in System.IO.Ports.SerialPort.GetPortNames())
            {
                comboBoxSerialPort.Items.Add(com);
            }

            comboBoxSerialPort.SelectedIndex = 0;
            //sp1.BaudRate = 9600;
            Control.CheckForIllegalCrossThreadCalls = false;
            //port.DataReceived += DataReceived;
            port.ReceivedBytesThreshold = 1;
            port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
   

            port.DtrEnable = true;//获取或设置一个值，该值在串行通信过程中启用数据终端就绪 (DTR) 信号。
            port.RtsEnable = true;//获取或设置一个值，该值指示在串行通信中是否启用请求发送 (RTS) 信号
                                  //设置数据读取超时为1秒
            port.ReadTimeout = 1000;

           // port.Close();
        }

        private void DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            
            
            if (port.IsOpen)     //判断是否打开串口
            {
                //输出当前时间
                DateTime dt = DateTime.Now;
                //textBoxRecieveData.Text += dt.GetDateTimeFormats('f')[0].ToString() + "\r\n";
                try
                {
                    int buffer= port.BytesToRead;
                    Byte[] receivedData = new Byte[buffer];        //创建接收字节数组
                    port.Read(receivedData, 0, receivedData.Length);         //读取数据
                    //AddContent(new UTF8Encoding().GetString(receivedData));//用万能的UTF8可以传输中文不会乱码
                    //AddContent(new ASCIIEncoding().GetString(receivedData));//用万能的UTF8可以传输中文不会乱码
                    StringBuilder sb = new StringBuilder();
                    //sb.Append("recieved (" + buffer + "):bytes, type:"+e.EventType+")");
                    for(int i=0;i<receivedData.Length;i++)
                    {
                        sb.Append(receivedData[i].ToString() + " ");
                    }
                    AddContent(sb.ToString());
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message, "出错提示!!!!!");
                    textBoxSendData.Text = "";
                }
            }
            else
            {
                MessageBox.Show("请打开某个串口", "错误提示");
            }
        }

        private void AddContent(string content)
        {
            this.BeginInvoke(new MethodInvoker(delegate
            {
                textBoxRecieveData.AppendText(content);
                textBoxRecieveData.AppendText("\r\n");
                //记录收到的字符个数
                //lblRevCount.Text = (int.Parse(lblRevCount.Text) + content.Length).ToString();
            }));
        }

        private void btnOpenSerialPort_Click(object sender, EventArgs e)
        {
            //serialPort1.IsOpen
            if (!port.IsOpen)
            {
                try
                {
                    //设置串口号
                    string serialName = comboBoxSerialPort.SelectedItem.ToString();
                    port.PortName = serialName;

                    //设置各“串口设置”
                    string strBaudRate = comboBoxBaudRate.Text;
                    string strDateBits = textBoxData.Text;
                    string strStopBits = comboBoxStop.Text;
                    Int32 iBaudRate = Convert.ToInt32(strBaudRate);
                    Int32 iDateBits = Convert.ToInt32(strDateBits);

                    port.BaudRate = iBaudRate;       //波特率
                    port.DataBits = iDateBits;       //数据位
                    switch (comboBoxStop.Text)            //停止位
                    {
                        case "0":
                            port.StopBits = StopBits.None;
                            break;
                        case "1":
                            port.StopBits = StopBits.One;
                            break;
                        case "1.5":
                            port.StopBits = StopBits.OnePointFive;
                            break;
                        case "2":
                            port.StopBits = StopBits.Two;
                            break;
                        default:
                            MessageBox.Show("Error：参数不正确!", "Error");
                            break;
                    }
                    switch (comboBoxCheck.Text)             //校验位
                    {
                        case "无":
                            port.Parity = Parity.None;
                            break;
                        case "奇校验":
                            port.Parity = Parity.Odd;
                            break;
                        case "偶校验":
                            port.Parity = Parity.Even;
                            break;
                        default:
                            MessageBox.Show("Error：参数不正确!", "Error");
                            break;
                    }

                    if (port.IsOpen == true)//如果打开状态，则先关闭一下
                    {
                        port.Close();
                    }

                    //设置必要控件不可用
                    comboBoxSerialPort.Enabled = false;
                    comboBoxBaudRate.Enabled = false;
                    textBoxData.Enabled = false;
                    comboBoxStop.Enabled = false;
                    comboBoxCheck.Enabled = false;
                    port.Open();     //打开串口
                    btnOpenSerialPort.Text = "关闭串口";
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Error:" + ex.Message, "Error");
                    return;
                }
            }
            else
            {
                //恢复控件功能
                //设置必要控件不可用
                comboBoxSerialPort.Enabled = true;
                comboBoxBaudRate.Enabled = true;
                textBoxData.Enabled = true;
                comboBoxStop.Enabled = true;
                comboBoxCheck.Enabled = true;
                port.Close();                    //关闭串口
                btnOpenSerialPort.Text = "打开串口";
            }
        }

        private void btnSendData_Click(object sender, EventArgs e)
        {
            port.Encoding = this.EncodingType;
            port.DiscardInBuffer();
            port.DiscardOutBuffer();
            byte[] buffer = new byte[] { 0x55, 0x01, 0x33, 0x89 };
            port.Write(buffer, 0, 4);
            //port.WriteLine(this.textBoxSendData.Text);
            
        }
    }
}
